<template>
  <CollapsibleSection
    title="个人史"
    :is-expanded="isExpanded"
    @toggle="$emit('toggle')"
  >
    <!-- 表单 -->
    <div class="form-container">
      <p class="tip">系统性个人史记录，评估生活方式与环境因素对健康的影响</p>

      <form>
        <!-- 1. 生活与饮食习惯 -->
        <div class="section">
          <div class="section-title">
            <span class="section-number">1</span>
            <span>生活与饮食习惯</span>
          </div>

          <!-- 吸烟史 -->
          <div class="form-group">
            <label for="smoking-history">吸烟史</label>
            <input
              id="smoking-history"
              class="form-input"
              type="text"
              v-model="form.lifestyle.smoking"
              placeholder="例如：吸烟20年，每天1包"
            />
            <p class="input-hint">请量化记录，如"吸烟20年，每天1包"，已戒烟者记录"已戒烟5年"</p>
          </div>

          <!-- 饮酒史 -->
          <div class="form-group">
            <label for="drinking-history">饮酒史</label>
            <input
              id="drinking-history"
              class="form-input"
              type="text"
              v-model="form.lifestyle.drinking"
              placeholder="例如：饮白酒20年，每日约100ml"
            />
            <p class="input-hint">请量化记录，避免使用"少量"、"适量"等模糊词汇</p>
          </div>

          <!-- 饮食偏好 -->
          <div class="form-group">
            <label>饮食偏好</label>
            <div class="checkbox-group">
              <div 
                class="checkbox-item" 
                :class="{ 'is-checked': form.lifestyle.dietPreferences.includes('高盐') }" 
                @click="toggleCheckbox(form.lifestyle.dietPreferences, '高盐')"
              >
                <input type="checkbox" :checked="form.lifestyle.dietPreferences.includes('高盐')" @change.stop /> 高盐
              </div>
              <div 
                class="checkbox-item" 
                :class="{ 'is-checked': form.lifestyle.dietPreferences.includes('高脂') }" 
                @click="toggleCheckbox(form.lifestyle.dietPreferences, '高脂')"
              >
                <input type="checkbox" :checked="form.lifestyle.dietPreferences.includes('高脂')" @change.stop /> 高脂
              </div>
              <div 
                class="checkbox-item" 
                :class="{ 'is-checked': form.lifestyle.dietPreferences.includes('高糖') }" 
                @click="toggleCheckbox(form.lifestyle.dietPreferences, '高糖')"
              >
                <input type="checkbox" :checked="form.lifestyle.dietPreferences.includes('高糖')" @change.stop /> 高糖
              </div>
              <div 
                class="checkbox-item" 
                :class="{ 'is-checked': form.lifestyle.dietPreferences.includes('辛辣') }" 
                @click="toggleCheckbox(form.lifestyle.dietPreferences, '辛辣')"
              >
                <input type="checkbox" :checked="form.lifestyle.dietPreferences.includes('辛辣')" @change.stop /> 辛辣
              </div>
            </div>

            <div class="form-group">
              <label for="diet-restrictions">特殊饮食禁忌</label>
              <input
                id="diet-restrictions"
                class="form-input"
                type="text"
                v-model="form.lifestyle.dietRestrictions"
                placeholder="例如：素食、过敏食物等"
              />
            </div>
          </div>

          <!-- 作息习惯 -->
          <div class="form-group">
            <label for="sleep-habits">作息习惯</label>
            <textarea
              id="sleep-habits"
              class="form-input"
              rows="2"
              v-model="form.lifestyle.sleepHabits"
              placeholder="例如：长期熬夜、失眠等"
            ></textarea>
          </div>
        </div>

        <!-- 2. 职业与环境暴露史 -->
        <div class="section">
          <div class="section-title">
            <span class="section-number">2</span>
            <span>职业与环境暴露史</span>
          </div>

          <!-- 职业史 -->
          <div class="form-group">
            <label for="occupational-history">职业史</label>
            <input
              id="occupational-history"
              class="form-input"
              type="text"
              v-model="form.environment.occupationalHistory"
              placeholder="当前及既往职业"
            />
            <p class="input-hint">重点记录有无接触粉尘（矽肺）、化学品（苯、铅）、放射性物质等</p>
          </div>

          <!-- 居住环境 -->
          <div class="form-group">
            <label for="residential-environment">居住环境</label>
            <textarea
              id="residential-environment"
              class="form-input"
              rows="2"
              v-model="form.environment.residentialEnvironment"
              placeholder="有无地方病、传染病流行区旅居史（如血吸虫病、疟疾）"
            ></textarea>
          </div>
        </div>

        <!-- 3. 冶游史与性取向 -->
        <div class="section">
          <div class="section-title">
            <span class="section-number">3</span>
            <span>冶游史与性取向</span>
          </div>

          <p class="section-desc">（在保护隐私、建立信任后，于相关科室如皮肤科、感染科、妇科尤为重要）</p>

          <!-- 性伴侣情况 -->
          <div class="form-group">
            <label for="partner-status">性伴侣情况</label>
            <input
              id="partner-status"
              class="form-input"
              type="text"
              v-model="form.sexual.partnerStatus"
              placeholder="请描述"
            />
          </div>

          <!-- 有无不洁性行为史 -->
          <div class="form-group">
            <label>有无不洁性行为史</label>
            <div class="radio-group">
              <div 
                class="checkbox-item" 
                :class="{ 'is-checked': form.sexual.uncleanSexBehavior === '有' }" 
                @click="form.sexual.uncleanSexBehavior = '有'"
              >
                <input type="radio" :checked="form.sexual.uncleanSexBehavior === '有'" name="unclean-sex" tabindex="-1" /> 有
              </div>
              <div 
                class="checkbox-item" 
                :class="{ 'is-checked': form.sexual.uncleanSexBehavior === '无' }" 
                @click="form.sexual.uncleanSexBehavior = '无'"
              >
                <input type="radio" :checked="form.sexual.uncleanSexBehavior === '无'" name="unclean-sex" tabindex="-1" /> 无
              </div>
            </div>
          </div>

          <!-- 性取向 -->
          <div class="form-group">
            <label for="sexual-orientation">性取向</label>
            <select id="sexual-orientation" class="form-input" v-model="form.sexual.orientation">
              <option value="">请选择</option>
              <option value="heterosexual">异性恋</option>
              <option value="homosexual">同性恋</option>
              <option value="bisexual">双性恋</option>
              <option value="other">其他</option>
            </select>
          </div>

          <!-- 采取的保护措施 -->
          <div class="form-group">
            <label for="protection-measures">采取的保护措施</label>
            <textarea
              id="protection-measures"
              class="form-input"
              rows="2"
              v-model="form.sexual.protectionMeasures"
              placeholder="请描述"
            ></textarea>
          </div>
        </div>

        <!-- 4. 其他 -->
        <div class="section">
          <div class="section-title">
            <span class="section-number">4</span>
            <span>其他</span>
          </div>

          <!-- 吸毒史 -->
          <div class="form-group">
            <label for="drug-history">吸毒史</label>
            <textarea
              id="drug-history"
              class="form-input"
              rows="2"
              v-model="form.other.drugHistory"
              placeholder="种类、方式、年限"
            ></textarea>
          </div>

          <!-- 重大精神创伤史 -->
          <div class="form-group">
            <label for="trauma-history">重大精神创伤史</label>
            <textarea
              id="trauma-history"
              class="form-input"
              rows="2"
              v-model="form.other.traumaHistory"
              placeholder="请描述"
            ></textarea>
          </div>
        </div>

        <div class="form-group">
          <div class="checkbox-item" :class="{ 'is-checked': form.confirmed }" @click="form.confirmed = !form.confirmed">
            <input type="checkbox" :checked="form.confirmed" @change.stop />
            确认信息无误，提交记录
          </div>
        </div>

        <button type="submit" class="submit-btn" @click.prevent="onSubmit" :disabled="!form.confirmed">提交记录</button>
      </form>
    </div>
  </CollapsibleSection>
</template>

<script setup lang="ts">
import CollapsibleSection from '@/components/CollapsibleSection.vue'
import { reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'

// 存储键名
const STORAGE_KEY = 'personalHistoryFormData'

interface Props {
  isExpanded: boolean
}

interface Emits {
  (e: 'toggle'): void
}

defineProps<Props>()
defineEmits<Emits>()

const form = reactive({
  lifestyle: {
    smoking: '',
    drinking: '',
    dietPreferences: [] as string[],
    dietRestrictions: '',
    sleepHabits: ''
  },
  environment: {
    occupationalHistory: '',
    residentialEnvironment: ''
  },
  sexual: {
    partnerStatus: '',
    uncleanSexBehavior: '',
    orientation: '',
    protectionMeasures: ''
  },
  other: {
    drugHistory: '',
    traumaHistory: ''
  },
  confirmed: false
})

// 处理复选框点击（用于数组类型的复选框）
function toggleCheckbox(array: string[], value: string) {
  const index = array.indexOf(value)
  if (index > -1) {
    array.splice(index, 1)
  } else {
    array.push(value)
  }
}

// 深拷贝函数
function deepClone<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj))
}

// 保存表单数据到缓存
function saveFormData() {
  try {
    const formDataCopy = deepClone(form)
    Taro.setStorageSync(STORAGE_KEY, formDataCopy)
    console.log('✅ 个人史表单数据已保存到缓存')
  } catch (error: any) {
    console.error('❌ 保存表单数据失败:', error)
    Taro.showToast({
      title: '保存数据失败',
      icon: 'none',
      duration: 2000
    })
  }
}

// 从缓存读取表单数据
function loadFormData() {
  try {
    const savedData = Taro.getStorageSync(STORAGE_KEY)
    if (savedData) {
      const parsedData = typeof savedData === 'string' ? JSON.parse(savedData) : savedData
      if (parsedData && typeof parsedData === 'object') {
        // 深度合并数据
        if (parsedData.lifestyle) Object.assign(form.lifestyle, parsedData.lifestyle)
        if (parsedData.environment) Object.assign(form.environment, parsedData.environment)
        if (parsedData.sexual) Object.assign(form.sexual, parsedData.sexual)
        if (parsedData.other) Object.assign(form.other, parsedData.other)
        if (parsedData.confirmed !== undefined) form.confirmed = parsedData.confirmed
        
        // 确保数组字段是数组
        if (!Array.isArray(form.lifestyle.dietPreferences)) {
          form.lifestyle.dietPreferences = []
        }
        
        console.log('✅ 个人史表单数据已从缓存加载')
      }
    }
  } catch (error: any) {
    console.error('❌ 加载表单数据失败:', error)
  }
}

// 组件挂载时加载缓存数据
onMounted(() => {
  loadFormData()
})

function onSubmit() {
  // 保存数据到缓存
  saveFormData()
  
  // 这里可替换为真实提交逻辑
  Taro.showToast({
    title: '个人史记录提交成功！',
    icon: 'success',
    duration: 2000
  })
}
</script>

<style scoped>
.form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  padding: 18px;
}
.tip { 
  text-align: center; 
  margin-bottom: 20px; 
  color: #666; 
  font-size: 20px; 
  line-height: 1.6; 
}
.section { 
  margin-bottom: 26px; 
  padding-bottom: 20px; 
  border-bottom: 1px dashed #eee; 
}
.section-title { 
  display: flex; 
  align-items: center; 
  margin-bottom: 16px; 
  font-weight: 600; 
  font-size: 22px; 
  color: #333;
}
.section-number { 
  display: inline-flex; 
  align-items: center; 
  justify-content: center; 
  width: 32px; 
  height: 32px; 
  background-color: #2c80ff; 
  color: #fff; 
  border-radius: 50%; 
  margin-right: 10px; 
  font-size: 16px; 
  font-weight: 600;
}
.section-desc { 
  margin-bottom: 12px; 
  color: #666; 
  font-size: 18px; 
  line-height: 1.6;
}
.form-group { margin-bottom: 24px; }
label { 
  display: block; 
  margin-bottom: 12px; 
  font-weight: 600; 
  font-size: 20px; 
  color: #333; 
  line-height: 1.5; 
}

/* 所有输入框统一样式 - 优化字体、背景和边框 */
.form-input,
input[type='text'],
input[type='number'],
select,
textarea {
  width: 100%;
  padding: 22px 26px;
  border: 2px solid #d0d7de;
  border-radius: 12px;
  font-size: 24px !important;
  background-color: #f8f9fa !important;
  color: #333 !important;
  box-sizing: border-box;
  -webkit-appearance: none;
  appearance: none;
  line-height: 1.7;
  min-height: 64px;
  transition: all 0.3s ease;
  font-weight: 500;
  display: block;
}

.form-input:hover,
input[type='text']:hover,
input[type='number']:hover,
select:hover,
textarea:hover {
  border-color: #b0b7c0 !important;
  background-color: #f0f1f3 !important;
}

.form-input:focus,
input:focus,
input[type='text']:focus,
input[type='number']:focus,
select:focus,
textarea:focus {
  border-color: #2c80ff !important;
  background-color: #fff !important;
  outline: none;
  box-shadow: 0 0 0 4px rgba(44, 128, 255, 0.15) !important;
  transform: translateY(-1px);
}

textarea.form-input,
textarea {
  min-height: 150px;
  resize: vertical;
  font-family: inherit;
  font-size: 24px !important;
  line-height: 1.7;
  padding: 22px 26px;
  background-color: #f8f9fa !important;
  border: 2px solid #d0d7de;
  border-radius: 12px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.input-hint {
  font-size: 16px;
  color: #888;
  margin-top: 6px;
  line-height: 1.5;
}

.checkbox-group { 
  display: flex; 
  flex-direction: column; 
  gap: 16px; 
  margin-top: 10px; 
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 10px;
}

.checkbox-item { 
  display: flex; 
  align-items: center; 
  gap: 12px; 
  padding: 18px 16px; 
  background: #f9f9f9; 
  border-radius: 8px; 
  min-height: 60px;
  font-size: 20px;
  transition: all 0.2s ease;
  border: 2px solid #e9ecef;
  cursor: pointer;
  position: relative;
}

.checkbox-item:active { 
  background-color: #f0f0f0; 
}

/* 选中状态样式 */
.checkbox-item:has(input:checked),
.checkbox-item.is-checked {
  background-color: #e7f3ff !important;
  border-color: #2c80ff !important;
  border-width: 2px !important;
  box-shadow: 0 2px 8px rgba(44, 128, 255, 0.15);
}

.checkbox-item input[type="checkbox"],
.checkbox-item input[type="radio"] {
  width: 24px;
  height: 24px;
  min-width: 24px;
  min-height: 24px;
  cursor: pointer;
  accent-color: #2c80ff;
  flex-shrink: 0;
  margin: 0;
  pointer-events: none;
}

.checkbox-item input[type="checkbox"]:checked,
.checkbox-item input[type="radio"]:checked {
  accent-color: #2c80ff;
}

/* 选中时文字颜色和字重 - 针对 label 内的文本 */
.checkbox-item:has(input:checked),
.checkbox-item.is-checked {
  color: #2c80ff;
  font-weight: 600;
}

/* 确保选中时整个 checkbox-item 的文字都变色 */
.checkbox-item:has(input:checked) *,
.checkbox-item.is-checked * {
  color: #2c80ff;
  font-weight: 600;
}

/* 但保持 input 本身的样式 */
.checkbox-item:has(input:checked) input,
.checkbox-item.is-checked input {
  color: initial;
  font-weight: initial;
}

/* NutUI 组件样式统一 */
:deep(.nut-input) {
  font-size: 24px !important;
  background-color: #f8f9fa !important;
  border: 2px solid #d0d7de !important;
  border-radius: 12px !important;
  min-height: 64px !important;
  padding: 22px 26px !important;
}

:deep(.nut-input:focus) {
  border-color: #2c80ff !important;
  background-color: #fff !important;
  box-shadow: 0 0 0 4px rgba(44, 128, 255, 0.15) !important;
}

:deep(.nut-button) {
  font-size: 20px !important;
  min-height: 60px !important;
  font-weight: 600 !important;
  border-radius: 8px !important;
}

.submit-btn { 
  background: #2c80ff; 
  color: #fff; 
  border: none; 
  border-radius: 8px; 
  padding: 18px 24px; 
  font-size: 20px; 
  cursor: pointer; 
  width: 100%; 
  min-height: 60px; 
  margin-top: 20px;
  font-weight: 600;
  transition: all 0.2s ease;
  box-shadow: 0 4px 12px rgba(44, 128, 255, 0.3);
}
.submit-btn:active:not(:disabled) { background: #1a6fe0; }
.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }
</style>
